package com.ftf.tp.message.infrastructure.adapter.http;

import com.ftf.tp.common.constants.RedisConstant;
import com.ftf.tp.common.core.exception.BusinessException;
import com.ftf.tp.common.core.redis.utils.RedissonHelper;
import com.ftf.tp.common.security.constants.UserVO;
import com.ftf.tp.message.application.adapter.http.UserHttpAdapter;
import com.ftf.tp.user.client.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author tanghao
 * @date 2022/7/28
 */
@Slf4j
@Service
public class UserHttpAdapterImpl implements UserHttpAdapter {

    @Resource
    private UserFeign userFeign;

    @Resource
    private RedissonHelper redissonHelper;


    @Override
    public UserInfoDTO getCurrentUser() {
        UserVO userVO;
        try {
            //获取passport登陆的基础用户信息log
            userVO = (UserVO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            log.error("当前用户未登录", e);
            throw new BusinessException("当前用户未登录");
        }
        UserInfoDTO userInfoDTO;
        Object userInfoByCache = redissonHelper.getValue(RedisConstant.TP_USER_INFO + userVO.getUserId());
        if (ObjectUtils.isEmpty(userInfoByCache)) {
            //缓存中没有,去用户服务获取
            userInfoDTO = userFeign.getCurrentUser();
            //将数据库里的数据存入缓存
            redissonHelper.setValue(RedisConstant.TP_USER_INFO + userVO.getUserId(), userInfoDTO);
        } else {
            userInfoDTO = (UserInfoDTO) userInfoByCache;
        }
        return userInfoDTO;
    }
}
